package category_eng.client;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;

public class ProductList extends Composite{
	VerticalPanel page = new VerticalPanel();
	Grid grid = new Grid(4,2);
	int currPage = 1;
	String query;
	HorizontalPanel anchorPage = new HorizontalPanel();
	public ProductList() {
		super();
	}
	public ProductList(String q) {
		super();
		query=q;
		grid.setStyleName("gwt-Grid-list");
		initWidget(page);
		page.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		if(q.indexOf("search=")!=-1){
			processSearch(q.substring(8));
		}else{
			getProductsMap();
		}
	}
	public void getProductsMap() {
		String url = GWT.getModuleBaseURL() + URL.encode("getDTOService") + URL.encode(query);//"?category=0"
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET,url);
		try {
			builder.sendRequest(null, new GetContentRequestCallback());
		} catch (RequestException e) {
		}
	}
	public void getProductDetail(String pid) {
		String url = GWT.getModuleBaseURL() + URL.encode("getDetailService") + URL.encode("?id="+pid+"&lang=eng");
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET,url);
		try {
			builder.sendRequest(null, new GetDetailRequestCallback());
		} catch (RequestException e) {
		}
	}
	private void listDetail(Map<String,String> map){
			page.clear();
			FlexTable ret = new FlexTable();
			ret.setWidget(0, 0, new HTML("<img src='/static/img/products/detail/"+(String)map.get("ID")+".jpg'>"));//new Image("/static/img/products/detail/"+(String)map.get("ID")+".jpg"));
			ret.setWidget(1, 0, new HTML("<p align='center'><strong>Product Name:"+(String)map.get("Title")+"</strong></p>"));
			ret.setWidget(2, 0, new HTML("<p align='left'><strong>Product Attribute:</strong></p>"));
			map.remove("Title");
			map.remove("ID");
			FlexTable grid = new FlexTable();
			grid.setBorderWidth(1);
			int row=0;
			for(String s:map.keySet()){
				grid.setHTML(row, 0, "<span style='font-size:12;'>"+s+"</span>");
				grid.getCellFormatter().setWidth(row, 0, "80px");
				grid.getCellFormatter().setAlignment(row, 0, HasHorizontalAlignment.ALIGN_LEFT, HasVerticalAlignment.ALIGN_TOP);
				grid.setHTML(row, 1, "<span style='font-size:12;'>"+(String)map.get(s)+"</span>");
				grid.getCellFormatter().setAlignment(row, 1, HasHorizontalAlignment.ALIGN_LEFT, HasVerticalAlignment.ALIGN_TOP);
				row++;
			}
			ret.setWidget(3, 0, grid);
			ret.getFlexCellFormatter().setAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER,HasVerticalAlignment.ALIGN_BOTTOM);
			page.add(ret);
			page.add(new HTML("<p align=right><a href='/products_eng.jhtml'><-Return</a></p>"));
	}
		
	  private Map<Integer,String> filterProducts(Map<Integer, String> products){
			 Map<Integer,String> ret= new HashMap<Integer,String>();
			 Integer totalCount = new Integer(products.size());
			 int value = totalCount/8;
			 Integer totalPage = totalCount % 8 == 0 ? new Integer(value):new Integer(value+1);
			 if(currPage < 1) currPage = 1;
			 if(currPage > totalPage) currPage = totalPage;
			 int productPos = 0;
			 for(Integer id:products.keySet()){
			  if(productPos > currPage * 8 - 1) break;
			  if(productPos < (currPage - 1) * 8) {productPos++;continue;}
			  ret.put(id, products.get(id));
			  productPos++;
			 }
		  return ret;
	  }
	  
		protected void getListTable(Map<Integer,String> products, int size){
			page.clear();
			grid.clear();
			int i=0;
			for(Integer pid:products.keySet()){
				int row = i / 2;
				int col = i % 2;
				grid.setWidget(row, col, listElement(new String[]{pid.toString(),products.get(pid)}));
				i++;
				if(i>products.size())break;
			}
			page.add(grid);
			loadPageAnchor(size);
		}
		
		private FlexTable listElement(String[] pinfo){
			FlexTable ret = new FlexTable();
			ret.setStyleName("gwt-Grid-cell");
//			Image image = new Image("");
//			image.setUrl("/static/img/products/browse/"+pinfo[0]+".jpg");
//			image.setAltText(pinfo[1]);
//			HTML html = new HTML("<a href='/item.jhtml?id="+pinfo[0]+"&lang=eng'><img src='/static/img/products/browse/"+pinfo[0]+".jpg'></a>");
			DetailHandler handler = new DetailHandler(pinfo[0]);
			ret.addClickHandler(handler);
			HTML html = new HTML("<a href='#'><img src='/static/img/products/browse/"+pinfo[0]+".jpg'></a>");

			Anchor ia = new Anchor();
			Grid nameModel = new Grid(3,1);
			nameModel.setStyleName("gwt-Grid-rightcol");
			String name="";
			String model="";
			if(pinfo[1].indexOf("_")==-1){
				name = pinfo[1];
			}else{
				name = pinfo[1].substring(0,pinfo[1].indexOf("_"));
				model = pinfo[1].substring(pinfo[1].indexOf("_")+1);
			}
			ia.setText(name);
			ia.setHref("#");
			ia.setStyleName("product-title");
			nameModel.setWidget(0,0,ia);
			if(!model.equals("")){
				Anchor ma = new Anchor();
				ma.setText("Model："+model);
				ma.setHref("#");//"/item.jhtml?id="+pinfo[0]);
				ma.setStyleName("product-title");
				nameModel.setWidget(1,0,ma);
			}
			HTML detailHtml = new HTML("<a href='#'><img src='/static/img/products/viewDetail_eng.gif'></a>");
			nameModel.setWidget(2,0,detailHtml);
			ret.getCellFormatter().setAlignment(0, 1,HasHorizontalAlignment.ALIGN_LEFT, HasVerticalAlignment.ALIGN_BOTTOM);
			ret.getCellFormatter().setWidth(0, 0,"130px");
			ret.getCellFormatter().setHeight(0, 0,"82px");
			nameModel.getCellFormatter().setAlignment(0, 0,HasHorizontalAlignment.ALIGN_LEFT, HasVerticalAlignment.ALIGN_BOTTOM);
			nameModel.getCellFormatter().setAlignment(1, 0,HasHorizontalAlignment.ALIGN_LEFT, HasVerticalAlignment.ALIGN_BOTTOM);
			nameModel.getCellFormatter().setAlignment(2, 0,HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_BOTTOM);
			ret.setWidget(0,0,html);
			Grid nameGrid = new Grid(1,2);
			nameGrid.getCellFormatter().setAlignment(0, 0,HasHorizontalAlignment.ALIGN_LEFT, HasVerticalAlignment.ALIGN_TOP);
			nameGrid.getCellFormatter().setAlignment(0, 1,HasHorizontalAlignment.ALIGN_LEFT, HasVerticalAlignment.ALIGN_TOP);
			nameGrid.setWidget(0, 0, new HTML("<a href='/item.jhtml?id="+pinfo[0]+"'><img src='/static/img/products/name.gif'></a>"));
			nameGrid.setWidget(0, 1, nameModel);
			nameGrid.setWidth("180px");
			ret.setWidget(0,1,nameGrid);
			ret.setWidth("330px");
			ret.setHeight("140px");
			ret.setBorderWidth(0);
			return ret;
		}
		
		private void loadPageAnchor(int totalCount){
			anchorPage.clear();
			int value = totalCount/8;
			Integer totalPage = totalCount % 8 == 0 ? new Integer(value):new Integer(value+1);
			if (currPage > 1) {
				Label lastPage = new Label("Prev.");
				anchorPage.add(lastPage);
				lastPage.addClickHandler(new ClickHandler() {
					public void onClick(ClickEvent event) {
						currPage -= 1;
						getProductsMap();
					}
				});
			} 
			for(int i=1;i<=totalPage;i++){
				if (currPage == i) {
					Label pageLabel = new Label(new Integer(i).toString());
					pageLabel.setStylePrimaryName("pageLabel");
					anchorPage.add(pageLabel);
				} else {
					Anchor pageAnchor = new Anchor(new Integer(i).toString());
					final int j = i;
					pageAnchor.addClickHandler(new ClickHandler() {
						public void onClick(ClickEvent event) {
							currPage = j;
							getProductsMap();
						}
					});
					anchorPage.add(pageAnchor);
				}
			}
			anchorPage.setStylePrimaryName("pageAnchor");
			if (currPage < totalPage) {
				Anchor nextPage = new Anchor("Next>>");
				anchorPage.add(nextPage);
				nextPage.addClickHandler(new ClickHandler() {
					public void onClick(ClickEvent event) {
						currPage += 1;
						getProductsMap();
					}
				});
			}
			HorizontalPanel sp = new HorizontalPanel(); 
			sp.add(anchorPage);
			sp.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
			page.add(sp);
		}
		
		
		private class GetContentRequestCallback implements RequestCallback {
			public GetContentRequestCallback() {
				super();
			}
			public void onError(Request request, Throwable exception) {
			}

			public void onResponseReceived(Request request, Response response) {
				Element noResultFound = Document.get().getElementById("noResultFound");
				if(noResultFound!=null)Document.get().getElementById("noResultFound").setInnerText("");

			   if (200 == response.getStatusCode()) {
			    	  String respText = response.getText();
//			    	  if(respText.equals(""))return;
//			    	  Map<Integer,String> map = new HashMap<Integer,String>();
//						JSONValue respValue = JSONParser.parseLenient(respText);
//						JSONArray trArray = respValue.isArray();
//						if(trArray.size()>0){
//							for(int i=0;i<trArray.size();i++){
//								JSONObject jo = trArray.get(i).isObject();
//								double d= jo.get("ID").isNumber().doubleValue();
//								map.put(new Integer((int)d), jo.get("Title").isString().stringValue());
//							}
//						}
//						int size = map.size();
//						getListTable(filterProducts(map),size);
			    	  processSearch(respText);
		      } 
			}
		}
		private class GetDetailRequestCallback implements RequestCallback {
			public GetDetailRequestCallback() {
				super();
			}
			public void onError(Request request, Throwable exception) {
			}

			public void onResponseReceived(Request request, Response response) {
			   if (200 == response.getStatusCode()) {
			    	  String respText = response.getText();
			    	  if(respText.equals(""))return;
			    	  Map<String,String> map = new HashMap<String,String>();
						JSONValue respValue = JSONParser.parseLenient(respText);
						JSONArray trArray = respValue.isArray();
						if(trArray.size()>0){
							for(int i=0;i<trArray.size();i++){
								JSONObject jo = trArray.get(i).isObject();
								String name= jo.get("AttrName").isString().stringValue();
								String value= jo.get("AttrValue").isString().stringValue();
								map.put(name, value);
							}
						}
						listDetail(map);
		      } 
			}
		}
		private class DetailHandler implements ClickHandler{
			String pid;
			public DetailHandler(String id) {
				pid = id;
			}
			public void onClick(ClickEvent event) {
				getProductDetail(pid);
			}
			
		}
		private void processSearch(String searchResult){
			if(searchResult==null || searchResult.equals(""))
				return;
	    	  Map<Integer,String> map = new HashMap<Integer,String>();
				JSONValue respValue = JSONParser.parseLenient(searchResult);
				JSONArray trArray = respValue.isArray();
				if(trArray.size()>0){
					for(int i=0;i<trArray.size();i++){
						JSONObject jo = trArray.get(i).isObject();
						double d= jo.get("ID").isNumber().doubleValue();
						map.put(new Integer((int)d), jo.get("Title").isString().stringValue());
					}
				}
				int size = map.size();
				getListTable(filterProducts(map),size);
		}
}
